package pers.mobian.springforth;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Date 2021/7/12 22:04
 * @Created mobian
 * @Description spring中bean的生命周期：先实例化（InstantiationAwareBeanPostProcessor中扩展实现类） 再初始化（BeanPostProcessor中实现）
 */
@Component
public class MyBeanPostProcessorInstance implements InstantiationAwareBeanPostProcessor {

	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		if ("userService2".equals(beanName)) {
			System.out.println("实例化————前的方法");
//			return  new Object();
//			return  new UserService2();
			return null;
		}
		return null;
	}

	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {

		if (beanName.equals("userService2")) {
			System.out.println("实例化————后的方法");
		}

		return true;
	}

	@Override
	public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
		return null;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

		if (beanName.equals("userService2")) {
			System.out.println("初始化————之前的方法的之前的方法");


			for (Method method : bean.getClass().getMethods()) {
				PostConstruct annotation = method.getAnnotation(PostConstruct.class);
				if (annotation != null) {
					try {
						System.out.print("模拟内部注解反射执行的方法：");
						method.invoke(bean);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("userService2")) {
			System.out.println("初始化————之后的方法");
		}
		return null;
	}
}
